<?php

class Empeval_LpImport_PositionsImport {
	
	public function start() {		
		$lpPositions = LpPositionsBaseQuery::create()->find()->toArray('Id');
		$positions = EmpevalPositionsQuery::create()->find()->toArray('ExtId');
		$newPositions = array_diff_assoc($lpPositions, $positions);
		$con = Propel::getConnection('vgp_empeval');
		$con->beginTransaction();
		try {
			foreach ($newPositions as $lpNew) {
				$new = new EmpevalPositions();
				$new->setExtId($lpNew['Id']);
				$new->setNamePl($lpNew['NamePl']);
				$new->setNameEn($lpNew['NameEn']);
				$new->setActive($lpNew['Type'] == 'Aktualne');
				$new->save($con);
			}
			$con->commit();
		} catch (Exception $e) {
			$con->rollBack();
			throw $e;
		}
		
		$userPositions = EmpevalUserPositionsQuery::create()
		->useUsersQuery()
			->filterById(20, Criteria::GREATER_EQUAL)
		->endUse()
		->leftJoinPositions()
		->with('Users')
		->with('Positions')
		->find();
		$con = Propel::getConnection('vgp_empeval');
		$con->beginTransaction();
		try {
			foreach ($userPositions as $userPosition) {
				$fromto = LpUmowyStanowiskaQuery::create()
				->withColumn('MIN(DataOd)', 'ActiveDate')
				->withColumn("CASE WHEN MAX(ISNULL(DataDo, '2100-01-01')) = '2100-01-01' THEN NULL ELSE MAX(DataDo) END", 'DeactiveDate')
				->filterByLogoId($userPosition->getUsers()->getExtId())
				->filterByPositionId($userPosition->getPositions()->getExtId())
				->groupBy('PositionId')
				->select('PositionId')
				->findOne();
				if ($fromto === null)
					continue;
				$userPosition->setActiveDate($fromto['ActiveDate']);
				$userPosition->setDeactiveDate($fromto['DeactiveDate']);
				$userPosition->save($con);
			}
			$con->commit();
		} catch (Exception $e) {
			$con->rollBack();
			throw $e;
		}
	}
		
}